package com.qjdchina.sku.front.web.exhandler;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qjdchina.sku.service.enums.SkuResultCode;
import org.springframework.beans.TypeMismatchException;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

@Component
public class TypeMissMatchExceptionHandler implements HandlerExceptionResolver,PriorityOrdered {
	
	/**
	 *  spring的BindException统一处理
	 */
    @Override  
    public ModelAndView resolveException(HttpServletRequest request,  
            HttpServletResponse response, Object object, Exception exception) {  
        if(exception instanceof BindException || exception instanceof TypeMismatchException){  
        	ModelAndView mav = new ModelAndView();
        	MappingJacksonJsonView view = new MappingJacksonJsonView();
            Map<String, Object> attributes = new HashMap<String,Object>();
            attributes.put("code", SkuResultCode.DATA_ERROR.getCode());
            attributes.put("data", null);
            attributes.put("message", SkuResultCode.DATA_ERROR.getMessage());
            view.setAttributesMap(attributes);
            mav.setView(view);
            return mav;
        }  
        return null;  
    }

	@Override
	public int getOrder() {
		return 0;
	}  
}  